﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using JCTimes.DomainModel.Repository;
using JCTimes.Portal.Infrastructure;
using JCTimes.Portal.Models;
using JCTimes.DomainModel.Entity;

namespace JCTimes.Portal.Controllers
{
    [Permission]
    public class SystemController : Controller
    {
        //
        // GET: /System/
        private IUserRepository usrRep;
        private IRoleRepository roleRep;
        private ILoginLogRepository loginRep;

        public SystemController(IUserRepository usrRepository, IRoleRepository roleRepository, ILoginLogRepository loginRepository)
        {
            this.usrRep = usrRepository;
            this.roleRep = roleRepository;
            this.loginRep = loginRepository;
        }

        /// <summary>
        /// Welcome page.
        /// </summary>
        /// <returns>Welcome page.</returns>
        [SessionAllowed]
        public ActionResult Index()
        {
            //ViewBag.Title = "戴尔零售出样管理系统";
            return View(viewName: "Welcome");
        }


        /// <summary>
        /// Login page.
        /// </summary>
        /// <returns>Login page.</returns>
        [Anonymous]
        public ActionResult Login()
        {
            return View();
        }

        [Anonymous]
        public ActionResult About()
        {
            return View();
        }

        [Anonymous]
        public ActionResult Concat()
        {
            return View();
        }

        [Anonymous]
        public ActionResult Customer()
        {
            return View();
        }

        [Anonymous]
        public ActionResult Products()
        {
            return View();
        }


        /// <summary>
        /// Login page.
        /// </summary>
        /// <param name="Usr">User name.</param>
        /// <param name="Pwd">Password.</param>
        /// <param name="ValidCode">Validation code.</param>
        /// <returns>If login success then redirect to welcome page, else show errors.</returns>
        [Anonymous]
        [HttpPost]
        public ActionResult Login(string Usr, string Pwd, string ValidCode)
        {
            if (!string.Equals(ValidCode, Session["ValidCode"] + ""))
            {
                TempData["Error"] = "验证码不正确!";
            }
            else
            {
                try
                {
                    var md5pwd = CM.GetMd5Password(Pwd);
                    var user = usrRep.Find(
                            u => u.UserName.ToLower() == Usr.Trim().ToLower() && u.Password == md5pwd && u.Flag == 0);
                    bool userIsExists = usrRep.Find(u => u.UserName == Usr.Trim()) != null;
                    if (user != null)
                    {
                        var role = roleRep.Find(user.RoleID);
                        //var region = usrRep.GetRegionById(user.RegionID);
                        var userInfo = new UserInfo
                        {
                            UserID = user.ID,
                            UserName = user.UserName,
                            Name = user.Name,
                            RoleID = user.RoleID,
                            RoleName = (role != null ? role.RoleName : null),
                            ParentID = user.ParentID
                        };
                        SessionHelper.CurrUser = userInfo;

                        //添加用户登录日志
                        LoginLog llinfo = new LoginLog();
                        llinfo.ID = Guid.NewGuid().ToString();
                        llinfo.UsersID = user.ID;
                        llinfo.CreateDate = System.DateTime.Now;
                        loginRep.Add(llinfo);
                        loginRep.SaveChanges();

                        return RedirectToAction("Index");
                    }
                    else
                    {
                        TempData["Error"] = "用户名或密码不正确!";
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog(ex.Message, ex);
                    TempData["Error"] = "出错了";
                }
            }
            return View();
        }

        //[Anonymous]
        //[HttpPost]
        //public ActionResult Login(string Usr, string Pwd)
        //{
        //    try
        //    {
        //        var md5pwd = CM.GetMd5Password(Pwd);
        //        var user = usrRep.Find(
        //                u => u.UserName.ToLower() == Usr.Trim().ToLower() && u.Password == md5pwd && u.Flag == 0);
        //        bool userIsExists = usrRep.Find(u => u.UserName == Usr.Trim()) != null;
        //        if (user != null)
        //        {
        //            var role = roleRep.Find(user.RoleID);
        //            //var region = usrRep.GetRegionById(user.RegionID);
        //            var userInfo = new UserInfo
        //            {
        //                UserID = user.ID,
        //                UserName = user.UserName,
        //                Name = user.Name,
        //                RoleID = user.RoleID,
        //                RoleName = (role != null ? role.RoleName : null),
        //                ParentID = user.ParentID
        //            };
        //            SessionHelper.CurrUser = userInfo;

        //            //添加用户登录日志
        //            LoginLog llinfo = new LoginLog();
        //            llinfo.ID = Guid.NewGuid().ToString();
        //            llinfo.UsersID = user.ID;
        //            llinfo.CreateDate = System.DateTime.Now;
        //            loginRep.Add(llinfo);
        //            loginRep.SaveChanges();

        //            return RedirectToAction("Index");
        //        }
        //        else
        //        {
        //            TempData["Error"] = "用户名或密码不正确!";
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        LogHelper.WriteLog(ex.Message, ex);
        //        TempData["Error"] = "出错了";
        //    }
        //    return View();
        //}

        /// <summary>
        /// Get validation code image.
        /// </summary>
        /// <returns>Image</returns>
        [Anonymous]
        public ActionResult GetImgVerifyChars()
        {
            string rndNum = Rnd.GetRandNum(4);
            Session["ValidCode"] = rndNum;
            //CookieHelper.SetCookie("ValidCode", rndNum);
            // 计算图片大小
            System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((rndNum.Length * 12.5)), 25);
            Graphics g = Graphics.FromImage(image);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();

            try
            {
                //生成随机生成器
                Random random = new Random();

                //清空图片背景色
                g.Clear(Color.White);

                //画图片的背景噪音线
                for (int i = 0; i < 25; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);

                    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }

                Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
                System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                g.DrawString(rndNum, font, brush, 2, 2);

                //画图片的前景噪音点
                for (int i = 0; i < 100; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);

                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }

                //画图片的边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);


                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                Response.ClearContent();
                Response.ContentType = "image/Gif";
                Response.BinaryWrite(ms.ToArray());
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
            return File(ms.ToArray(), @"image/Gif");
        }

        /// <summary>
        /// Log off.
        /// </summary>
        /// <returns>Log in page.</returns>
        [Anonymous]
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            Session.Abandon();
            return RedirectToAction("Login", "System");
        }

        /// <summary>
        /// Change password for current user.
        /// </summary>
        /// <returns>Form</returns>
        public ActionResult ChangePassword()
        {
            return View();
        }

        /// <summary>
        /// Change password for current user.
        /// </summary>
        /// <param name="changePassword">Form collections of change password</param>
        /// <returns>Change result in json.</returns>
        [HttpPost]
        public JsonResult ChangePassword(ChangePassword changePassword)
        {
            try
            {
                var md5pwd = CM.GetMd5Password(changePassword.OldPassword);
                var usr = usrRep.Find(SessionHelper.CurrUser.UserID);
                if (usr != null)
                {
                    if (!string.Equals(usr.Password, md5pwd))
                    {
                        //ModelState.AddModelError("OldPassword", "密码不正确");
                        return Json("原密码不正确");
                    }
                    else
                    {
                        usr.Password = CM.GetMd5Password(changePassword.NewPassword);
                        usrRep.SaveChanges();
                        //return RedirectToAction("LogOff");
                        return Json("修改成功");
                    }
                }
                else
                {
                    //RedirectToAction("Login");
                    return Json("当前用户丢失, 请重新登陆");
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message, ex);
                return Json("出错了");
            }
        }

    }
}
